package view;

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.Color;

import  javax.swing.*;


import game.*;
/**
 * <p>This class encapsulates a grid of buttons used to represent a chess board.</p>
 * 
 * @author Mark Kelly
 * @version 3.0
 */
public class BoardPanel extends JPanel {
	private static final int DEFAULT_LENGTH = 8;	
	private static final long serialVersionUID = 5825156687073436652L;
	
	private ChessIcons icons;
	
	/**
	 * Creates a new instance of {@code BoardPanel}
	 */
	public BoardPanel() {
		super(new GridLayout(DEFAULT_LENGTH, DEFAULT_LENGTH));
		
		int width = DEFAULT_LENGTH;
		int height = DEFAULT_LENGTH;
		
		icons = new SpecialKnightIcons();
		
		for (int y = height; y > 0; y--)
			for (int x = 1; x <= width; x++)
				this.add(new BoardButton(new Point(x, y), (((x + y) % 2 != 0) ? Color.LIGHT_GRAY : Color.BLACK)));
	}
	
	/**
	 * <p>Adds an {@code ActionListener} to every button on the panel</p>
	 * @param al - the {@code ActionListener} to add
	 */
	public void addActionListener(ActionListener al) {
		for (Component c : this.getComponents())
			((JButton)c).addActionListener(al);
	}
	
	/**
	 * <p>Updates icons and text in this panel</p>
	 * @param b - the {@code ChessBoard}
	 */
	public void refresh(ChessBoard b) {
		Piece p = null;
		BoardButton bb = null;
		for (Component c : this.getComponents()) {
			bb = ((BoardButton)c);
			p = b.getPieceAt(bb.getLocation());
			if (p != null) {
				ImageIcon icon = icons.getIconForPiece(p);
				if (icon == null)
					bb.setText(p.getTeam().toLetter() + "" + p.toLetter());
				else
					bb.setIcon(icon);
			}
			else {
				bb.setText("");
				bb.setIcon(null);
			}
		}
	}
	
	/**
	 * <p>Adds a {@code Component} to this panel. It will only add {@code BoardButtons}.</p>
	 * 
	 * @return the c{@code Component} to add
	 */
	public Component add(Component c) {
		if (!(c instanceof BoardButton))
			return null;
		
		return super.add(c);
	}
	
	/**
	 * <p>Returns the {@code BoardButton} at the {@code Point} p</p>
	 * 
	 * @param p the {@code Point} for which we want a {@code BoardButton} reference
	 * @return the {@code BoardButton} located at {@code Point} p
	 */
	public BoardButton getButton (Point p)
	{
		for (Component c: this.getComponents()) {
			if (((BoardButton)c).getLocation().equals(p))
				return (BoardButton)c;
		}
		return null;
	}
}
